package com.iwithlong.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

/**
 * Write class comments here
 * <p/>
 * User: shenyongsheng
 * Date: 2016/6/2 11:29
 * version $Id: JsonUtil.java, v 0.1  11:29 Exp $
 */
public class JsonUtil {

    static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }


    /**
     * json转化为map
     * @param json
     * @return
     * @throws IOException
     */
    public static Map<String, Object> jsonToMap(String json) {
        try {
            Map<String, Object> map = objectMapper.readValue(json, Map.class);
            return map;
        } catch (IOException e) {
            throw new RuntimeException("json转map异常!", e);
        }
    }

    public static <T> T jsonToBean(String json, Class<T> beanClass) {
        try {

            return objectMapper.readValue(json, beanClass);
        } catch (IOException e) {
            throw new RuntimeException("json转bean异常!", e);
        }
    }

    public  static String beanToJson(Object obj){
        try {
            //去除 null 属性
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("bean转json异常!", e);
        }
    }
}
